package com.snapp.web.actions.file;

import java.io.File;

import javax.servlet.http.HttpServletRequest;

import com.snapp.util.object.model.ObjectModel;
import com.snapp.web.actions.Load;
import com.snapp.web.agents.FileAgent;
import com.snapp.web.agents.SNAppAgent;

public class Download extends Load {
	private File file = null;
	
	public String execute(HttpServletRequest req) {
		if (file == null) {
			try  {
				
				SNAppAgent sa = new SNAppAgent();
				ObjectModel object = sa.load("SNAPP_FILE", consolidateReadMap(req));
				FileAgent fa = new FileAgent();
				file = fa.byteArrayToFile((byte[])object.getBean().getProperty("file"), "tmp");
				
			} catch(Exception e) {
				setResults(RESULT_CODE_ERROR, "Error retrieving file");
				log("Error retrieving file!", e);
				return snappResponse(req);
			}
		}
		
		return fileResponse(req, getFile());
	}

	public File getFile() {
		return file;
	}

	public void setFile(File file) {
		this.file = file;
	}
}
